package cn.com.callback
import groovy.json.JsonSlurper
import groovy.swing.impl.DefaultAction
import groovy.xml.Namespace
import java.text.MessageFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.callback.CallBackInvoke
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher
import java.util.regex.Pattern

import java.util.HashMap;
import java.util.Map;
import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

import com.wisdge.dataservice.Result;
import cn.com.elite.Util;

public class GetDataInBound implements ServiceBackInvoke{
	private static final Log log=LogFactory.getLog(GetDataInBound.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		log.debug("-------------------------start GetDataInBound-----------------");
		log.debug("request----------------:"+request);

		String getMethod = request.getMethod();
		String callJson="";
		BufferedReader iny = null;

		def reJson = "";

		log.debug("getMethod:"+getMethod);
		/*if (getMethod.equals("GET")) {
		 log.debug("原始Get请求参数:"+request.getParameter("jsondata"));
		 callJson = getParamToJson(request.getParameter("jsondata"),"&");
		 log.debug("Get参数转化Json后callJson:"+callJson);
		 } else {
		 InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
		 iny = new BufferedReader(reader);
		 String line;
		 while ((line = iny.readLine()) != null) {
		 callJson += line;
		 }
		 log.debug("原始Post请求参数:"+callJson);
		 callJson=getParamToJson(callJson,"&");
		 log.debug("Post参数转化Json后callJson:"+callJson);
		 }*/

		//request对象封装的参数是以Map的形式存储的
		Map<String, Object> paramMap = request.getParameterMap();
		JSONObject paramJson = new JSONObject();
		JSONArray paramArray = new JSONArray();

		log.debug("request对象封装的参数Map--"+paramMap.toString());
		for(Map.Entry<String, Object> entry :paramMap.entrySet()){
			String paramName = entry.getKey();
			String[] paramValueArr = entry.getValue();
			String paramValue = "";

			for (int i = 0; paramValueArr!=null && i < paramValueArr.length; i++) {
				if (i == paramValueArr.length-1) {
					paramValue+=paramValueArr[i];
				}else {
					paramValue+=paramValueArr[i]+",";
				}
			}

			if(paramName.equals("cdr_ivr_flow")) {
				String[] paramArr = paramValue.split(",");
				paramArray = JSONArray.fromObject(paramArr);
				log.debug("--原始值String数组类型:"+paramArr.toString()+"  --转化值JSONArray类型:"+paramArray.toString());

				paramJson.element(paramName+"_Array", paramArray);

			}
			paramJson.put(paramName, paramValue);
			log.debug(MessageFormat.format("{0}={1}", paramName,paramValue));
		}
		callJson = paramJson.toString();
		log.debug("callJson:"+paramJson.toString());

		//生成任务ID
		def	deal_no = Util.getGuid();
		log.debug("自动生成任务ID:"+deal_no);
		def dataSourceID="dataSource";

		try{
			//解析Json
			def root=new JsonSlurper().parseText(callJson);
			//处理呼入挂机数据推送
			log.debug("处理呼入挂机数据推送开始。。。");
			def dxnum=root.data.size();
			log.debug("处理呼入挂机数据推送List数量:"+dxnum);

			def cdr_main_unique_id = "";//通话记录唯一标识
			def cdr_enterprise_id  = "";//企业Id
			def cdr_customer_number  = "";//客户号码
			def cdr_customer_area_code  ="";//呼入或外呼座席接听后的座席区号
			def cdr_customer_number_type = "";//来电或外呼客户号码类型: 手机/固话
			def cdr_start_time = "";//进入系统时间
			def cdr_answer_time = "";//系统接听时间
			def cdr_join_queue_time = "";//进队列时间
			def cdr_bridge_time = "";//桥接时间，留言时用作留言开始时间
			def cdr_end_time = "";//挂机时间
			def cdr_ivr_id = "";//ivr id
			def cdr_ivr_flow = "";//产品名称
			def cdr_call_type="";//呼叫类型
			def cdr_status="";//通话状态
			def cdr_mark="";//标识
			def cdr_gw_ip="";//网关地址
			def cdr_number_trunk="";//目的码
			def cdr_bridged_cno="";//呼入/呼出接听电话的座席号码
			def CDR="";//进件状态
			def cdr_record_file="";//录音文件名

			for(int i = 0;i<dxnum;i++) {
				log.debug("开始循环处理List:"+i);
				cdr_main_unique_id = "";
				cdr_enterprise_id = "";
				cdr_customer_number  = "";
				cdr_customer_area_code  = "";
				cdr_customer_number_type  ="";
				cdr_customer_area_code = "";
				cdr_start_time = "";
				cdr_answer_time = "";
				cdr_join_queue_time="";
				cdr_bridge_time="";
				cdr_end_time="";
				cdr_ivr_id="";
				cdr_ivr_flow="";
				cdr_call_type="";
				cdr_status="";
				cdr_mark="";
				cdr_gw_ip="";
				cdr_number_trunk="";
				cdr_bridged_cno="";
				CDR="";
				cdr_record_file="";

				log.debug("开始解析单个List数据...");
				cdr_main_unique_id = root.data.cdr_main_unique_id[i];
				cdr_enterprise_id = stringDeal(root.data.cdr_enterprise_id[i]);
				cdr_customer_number = stringDeal(root.data.cdr_customer_number[i]);
				cdr_customer_area_code = stringDeal(root.data.cdr_customer_area_code[i]);
				cdr_customer_number_type=stringDeal(root.data.cdr_customer_number_type[i]);
				cdr_customer_area_code=root.data.cdr_customer_area_code[i];

				cdr_ivr_id=stringDeal(root.data.cdr_ivr_id[i]);
				cdr_ivr_flow=stringDeal(root.data.cdr_ivr_flow[i]);

				cdr_call_type=stringDeal(root.data.cdr_call_type[i]);
				cdr_status=stringDeal(root.data.cdr_status[i]);
				cdr_mark=stringDeal(root.data.cdr_mark[i]);
				cdr_gw_ip=stringDeal(root.data.cdr_gw_ip[i]);

				cdr_number_trunk=stringDeal(root.data.cdr_number_trunk[i]);
				cdr_bridged_cno=stringDeal(root.data.cdr_bridged_cno[i]);
				CDR=stringDeal(root.data.CDR[i]);
				cdr_record_file=stringDeal(root.data.cdr_record_file[i]);

				cdr_start_time=root.data.cdr_start_time[i];
				log.debug("推送的cdr_start_time"+cdr_start_time);

				cdr_answer_time=root.data.cdr_answer_time[i];
				log.debug("推送的cdr_answer_time"+cdr_answer_time);

				cdr_join_queue_time=root.data.cdr_join_queue_time[i];
				log.debug("推送的cdr_join_queue_time"+cdr_join_queue_time);

				cdr_bridge_time=root.data.cdr_bridge_time[i];
				log.debug("推送的cdr_bridge_time"+cdr_bridge_time);

				cdr_end_time=root.data.cdr_end_time[i];
				log.debug("推送的cdr_end_time"+cdr_end_time);

				//解析时间戳
				def v_cdr_start_time,v_cdr_answer_time,v_cdr_join_queue_time,v_cdr_bridge_time,v_cdr_end_time;
				v_cdr_start_time = timeDeal(cdr_start_time);//进入系统时间
				v_cdr_answer_time = timeDeal(cdr_answer_time);//系统接听时间
				v_cdr_join_queue_time = timeDeal(cdr_join_queue_time);//进队列时间
				v_cdr_bridge_time = timeDeal(cdr_bridge_time);//桥接时间
				v_cdr_end_time = timeDeal(cdr_end_time);//挂机时间

				//判断推送数据是否重复
				def countNum = eliteBean.chaxun_sql("select count(*) as Count from tr_datainbound where cdr_main_unique_id='" + cdr_main_unique_id + "'",'dataSource');
				def Countnumj =countNum.get(0).get("Count");
				log.debug("判断通话唯一标识是否重复SQL:"+Countnumj);
				if(Countnumj<=0)
				{
					def insertSQL="insert into tr_datainbound(guid,deal_no,cdr_main_unique_id,cdr_enterprise_id,cdr_customer_number,cdr_customer_area_code,cdr_customer_number_type,cdr_start_time,cdr_answer_time,cdr_join_queue_time,cdr_bridge_time,cdr_end_time,cdr_ivr_id,cdr_ivr_flow,cdr_call_type,cdr_status,cdr_mark,cdr_gw_ip,cdr_number_trunk,cdr_bridged_cno,CDR,cdr_record_file,createddate,createby) values (UUID(),'"+deal_no+"','"+cdr_main_unique_id+"','"+cdr_enterprise_id+"','"+cdr_customer_number+"','"+cdr_customer_area_code+"','"+cdr_customer_number_type+"','"+v_cdr_start_time+"','"+v_cdr_answer_time+"','"+v_cdr_join_queue_time+"','"+v_cdr_bridge_time+"','"+v_cdr_end_time+"','"+cdr_ivr_id+"','"+cdr_ivr_flow+"','"+cdr_call_type+"','"+cdr_status+"','"+cdr_mark+"','"+cdr_gw_ip+"','"+cdr_number_trunk+"','"+cdr_bridged_cno+"','"+CDR+"','"+cdr_record_file+"',SYSDATE(),'SELITE')";
					log.debug("呼入挂机推送信息表处理SQL:"+insertSQL);
					eliteBean.update(insertSQL,dataSourceID);
				}
				else if(Countnumj>0)
				{
					def UpadateSQL="UPDATE tr_datainbound set cdr_enterprise_id='"+cdr_enterprise_id+"', cdr_customer_number='"+cdr_customer_number+"',cdr_customer_area_code='"+cdr_customer_area_code+"',cdr_customer_number_type='"+cdr_customer_number_type+"',cdr_start_time='"+v_cdr_start_time+"',cdr_answer_time='"+v_cdr_answer_time+"',cdr_join_queue_time='"+v_cdr_join_queue_time+"',cdr_bridge_time='"+v_cdr_bridge_time+"',cdr_end_time='"+v_cdr_end_time+"',cdr_ivr_id='"+cdr_ivr_id+"',cdr_ivr_flow='"+cdr_ivr_flow+"',cdr_call_type='"+cdr_call_type+"',cdr_status='"+cdr_status+"',cdr_mark='"+cdr_mark+"',cdr_gw_ip='"+cdr_gw_ip+"',cdr_number_trunk='"+cdr_number_trunk+"',cdr_bridged_cno='"+cdr_bridged_cno+"',CDR='"+CDR+"',cdr_record_file='"+cdr_record_file+"',modifydate=sysdate() where cdr_main_unique_id='" + cdr_main_unique_id + "'";
					log.debug("呼入挂机推送信息更新处理SQL:"+UpadateSQL);
					eliteBean.update(UpadateSQL,dataSourceID);
				}
				else
				{
					log.debug("忽略处理。。。。。。。。。");
				}


				reJson= "{\"result\":\"1\",\"description\":\"成功\"}";
				log.debug("GetDataInBound返回Json:"+reJson);
				return reJson;
			}
		}
		catch(Exception e)
		{
			log.debug("接口处理异常"+e.getMessage());
			reJson= "{\"result\":\"0\",\"description\":\"错误:"+e.getMessage()+"\"}";
			log.debug("GetDataInBound返回Json:"+reJson);
			rollBack(eliteBean, deal_no);
			return reJson;
		}

	}
	//异常回滚数据
	public rollBack(EliteBean eliteBean,String deal_no) {
		def deleteSQL="";
		deleteSQL="Delete From tr_datainbound Where Deal_No = '"+deal_no+"'";
		log.debug("删除主要信息表处理SQL:"+deleteSQL);
		eliteBean.update(deleteSQL,'dataSource');

	}

	//解析时间戳方法
	static String timeDeal(String time) {
		log.debug("待解析时间戳time:"+time);
		if (null != time && !"".equals(time)) {
			long timeLong = Long.parseLong(time);
			log.debug("开始解析时间戳time:" + timeLong);
			SimpleDateFormat confirme= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//时间格式化类
			log.debug("confirme " + confirme);
			return confirme.format(new Date(timeLong));
		}
		return "";
	}
	//处理字符串null
	static def stringDeal(def nullString) {
		log.debug("待解析字符串:"+nullString);
		def tempString="";
		if(!nullString.equals("")&&nullString!=null){
			log.debug("开始处理字符串:"+nullString);
			tempString = nullString;
		}
		else{
			log.debug("无效的字符串:"+nullString);
			tempString = "";
		}
		return tempString;
	}

	static long longDeal(String time) {
		long l=Long.parseLong(time);
		return l;
	}
}
